package userInterface;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JPanel;

import baseObject.IBrick;
import baseObject.IBrickBreaker;
import baseObject.IBrickBreakerObserver;
import baseObject.IBrickBreaker.TFinished;

@SuppressWarnings("serial")
public class BrickBreakerPanel extends JPanel implements Runnable, IBrickBreakerObserver{
	private IBrickBreaker brickBreaker;

	public void moveBall(){
		while(true){
			this.brickBreaker.moveBall();
			this.brickBreaker.calculateStep();
			this.repaint();
			try {
				Thread.sleep(5);
			} catch (InterruptedException e) {
				System.err.println(e);
			}
		}
	}
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D) g;
		if(this.brickBreaker != null && this.brickBreaker.isFinished() != TFinished.GAMEOVER){
			for(IBrick brick: this.brickBreaker.getWall().getListBrick()){
				if(brick.isBreakable()){
					if(brick.getResistance() > 0){
						g2.setColor(Color.black);
						g2.drawRect(brick.getX(), brick.getY(),brick.getWidth(), brick.getHeight());
					}
				}else{
					g2.setColor(Color.red);
					g2.fillRect(brick.getX(), brick.getY(),brick.getWidth(), brick.getHeight());
				}
			}
			g2.setColor(Color.black);
			g2.fillRect(this.brickBreaker.getPaddle().getX(),this.brickBreaker.getPaddle().getY(),
					this.brickBreaker.getPaddle().getWidth(), this.brickBreaker.getPaddle().getHeight());
			g2.setColor(Color.green);
			g2.fillOval(this.brickBreaker.getBall().getX(), this.brickBreaker.getBall().getY(), 
					this.brickBreaker.getBall().getWidth(), this.brickBreaker.getBall().getHeight());
		}else if(this.brickBreaker != null){
			g2.drawString("GAME OVER", (this.brickBreaker.getXMAX() / 2) - 50 , this.brickBreaker.getYMAX() / 2);
		}
		super.repaint();
	}

	public void paddleLeft(){
		this.brickBreaker.getPaddle().left();
	}

	public void paddleRight(){
		this.brickBreaker.getPaddle().right();
	}

	public TFinished gameState(){
		return this.brickBreaker.isFinished();
	}
	public void run() {
		this.moveBall();
	}

	public void changeEnvironment(IBrickBreaker brickBreaker) {
		this.brickBreaker = brickBreaker;
		this.repaint();
	}
}
